import APIConfig from "../config/api"
import exceptionMessage from "../config/exception-message"
import cache from "../enum/cache"
import User from "../model/user"
import wxToPromise from "../utils/wx"
class Http{

  static async request({url,data,method = 'GET',refetch = true}){

    let res
    try{
        res = await wxToPromise('request',{
        url:APIConfig.baseUrl + url,
        data,
        method,
        header:{
          token:wx.getStorageSync(cache.TOKEN)
        }
      })
    }catch(e){
      Http._showError(-1)
      throw new Error(e.errMsg)
    }


    /**
     * 1.代码写错
     * 2.无网络
     * 3.服务端超时
     */
  
        // 请求成功
        if(res.statusCode < 400){
          return res.data.data
        }

        

        // 请求失败
        if(res.statusCode == 401){
          // 令牌相关操作

          this.storeBindings = createStoreBindings(this,{
            store:timStore,
            fields:['sdkReady'],
            actions:{timLogout:'logout'},
          })

          if(res.data.error_code === 10001){

            if(this.sdkReady){
              this.timLogout()
            }

            wx.navigateTo({
              url:'/pages/login/login'
            })
            throw Error('请求未携带令牌')
          }
          // 如果用户令牌过期 则自动去获取令牌 执行请求
          if(refetch){
            return await Http._refetch({url,data,method,refetch})
          }
          if(this.sdkReady){
            this.timLogout()
          }
          
        }
        Http._showError(10001)




        const error = Http._generateMessage(res.data.message)
        throw Error(error !== '' ? error:'未知问题，请联系客服')

      
    
  }



  // 重新发起登录请求
  static async _refetch(data){
    await User.login()
    data.refetch = false
    return await Http.request(data)
  }


  static _showError(errorCode,message){
    let title = ''
    const errorMessage = exceptionMessage[errorCode]
    title = errorMessage || message || '未知异常'

    title = Http._generateMessage(title)
    
    // 弹窗
    wx.showToast({
      title,
      icon:'none',
      duration:3000,
    })
  }


  static _generateMessage(message){
    return typeof message === 'object' ? Object.values(message).join(';') : message

  }

}

export default Http